<template>
  <div class="app-container">
    <el-row :gutter="24">
      <!-- 选择菜单信息 -->
      <el-col :span="6" :xs="24" :style="conheight">

        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>已选菜品</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="hasOrderItem()">已下单菜品</el-button>
          </div>
          <div v-for="(item, index) in saleItemList" :key="item.productId">
            <el-row :gutter="24" v-if="item.productDescription !== null">
              <el-col :span="10"><img :src="item.productDescription.url" class="image"></el-col>
              <el-col :span="14">
                <el-row :gutter="20" style="margin-top:10px">
                  <el-col :span="11">{{ item.productDescription.productName }}</el-col>
                  <el-col :span="6">{{ item.productDescription.price }}</el-col>
                  <el-col :span="4">
                    <div class="grid-content bg-purple">
                      <el-button type="danger" size="mini" icon="el-icon-delete" circle
                        @click="delOrderItem(index, item)" />
                    </div>
                  </el-col>
                </el-row>
                <el-row style="margin-top:10px">
                  <el-col :span="6">
                    <el-input-number v-model="item.quantity" size="mini" :min="1"
                      @change="handleChangeQuantity(item)" />
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <el-row :gutter="24" v-if="item.taocan !== null">
              <el-col :span="10"><img src="http://43.138.211.217:9000/misp-minio/taocan.jpg" class="image"></el-col>
              <el-col :span="14">
                <el-row :gutter="20" style="margin-top:10px">
                  <el-col :span="11">{{ item.taocan.taocanName }}</el-col>
                  <el-col :span="6">{{ item.taocan.price }}</el-col>
                  <el-col :span="4">
                    <div class="grid-content bg-purple">
                      <el-button type="danger" size="mini" icon="el-icon-delete" circle
                        @click="delOrderItem(index, item)" />
                    </div>
                  </el-col>
                </el-row>
                <el-row style="margin-top:10px">
                  <el-col :span="6">
                    <el-input-number v-model="item.quantity" size="mini" :min="1"
                      @change="handleChangeQuantity(item)" />
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <el-divider />
          </div>

        </el-card>
      </el-col>
      <!-- 中间菜单 -->
      <el-col :span="12" :xs="24" :style="conheight">
        <el-card class="box-card">
          <!-- 搜索表单 -->
          <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
            <el-form-item label="菜品名称" prop="productSn">
              <el-input v-model="queryParams.productName" placeholder="请输入菜品名称" clearable size="small"
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <!-- 搜索按钮 -->
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane v-for="item in categoryOptions" :key="item.categoryId" :label="item.categoryName"
              :name="item.categoryId.toString()">
              <el-row>
                <el-col v-for="i in dataList" :key="i.productId" :span="6">
                  <el-card :body-style="{ padding: '0px' }" class="menuCard"
                    v-if="i.productState === '在售' || i.taocanStatus === '在售'">
                    <img :src="i.url" class="image">
                    <div style="padding: 14px;">
                      <span style="font-size: 15px">{{ i.productName }}</span>
                      <div class="bottom clearfix">
                        <span class="price">${{ i.price }}</span>
                        <el-button style="float: right; padding: 3px 0" type="text" class="el-icon-circle-plus-outline"
                          @click="enterItem(i)" />
                      </div>
                    </div>
                  </el-card>
                </el-col>
              </el-row>

              <!-- 分页加载 -->
              <el-pagination :current-page="queryParams.pageNum" :page-sizes="[5, 10, 20, 50,100]"
                :page-size="queryParams.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </el-tab-pane>
          </el-tabs>

        </el-card>
      </el-col>

      <!-- 订单信息操作 -->
      <el-col :span="6" :xs="24" :style="conheight">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>用户信息</span>
          </div>
          <div>
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="grid-content bg-purple">座位号</div>
              </el-col>
              <el-col :span="6" :offset="6">
                <div class="grid-content bg-purple">{{ seatData.seatNumber }}</div>
              </el-col>
            </el-row>
            <el-divider />
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="grid-content bg-purple">就餐人数</div>
              </el-col>
              <el-col :span="6" :offset="6">
                <div class="grid-content bg-purple">{{ orderInfo.customerNumber }}</div>
              </el-col>
            </el-row>
            <el-divider />
            <el-row :gutter="20">
              <el-col :span="6">
                <div class="grid-content bg-purple">订单号</div>
              </el-col>
              <el-col :span="16">
                <div class="grid-content bg-purple">{{ orderInfo.orderNo }}</div>
              </el-col>
            </el-row>
            <el-divider />
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="grid-content bg-purple">总金额</div>
              </el-col>
              <el-col :span="6" :offset="6">
                <div class="grid-content bg-purple">{{ orderInfo.total }}</div>
              </el-col>
            </el-row>
            <el-divider />
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="grid-content bg-purple">状态</div>
              </el-col>
              <el-col :span="6" :offset="6">
                <div class="grid-content bg-purple">
                  <el-tag size="small">{{ orderInfo.status }}</el-tag>
                </div>
              </el-col>
            </el-row>
            <el-divider />
            <el-row type="flex" justify="center">
              <el-button type="primary" round @click="handUpOrder()" :disabled="saleItemList.length == 0">挂起</el-button>
              <el-button type="success" round @click="pendingOrder()" :disabled="saleItemList.length == 0">下单
              </el-button>
            </el-row>
            <el-row type="flex" justify="center">
              <el-button type="danger" round @click="endOrder()" :disabled="orderInfo.status === '已备餐'">结算
              </el-button>
              <el-button type="danger" round @click="cancelOrder()">取消订单
              </el-button>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 已下单菜品 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body>
      <el-table :data="hasOrderItemList" style="width: 100%" max-height="450">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-form label-position="left" inline class="demo-table-expand" v-if="scope.row.itemIdentity === 1">
              <el-form-item label="商品名称">
                <span>{{ }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="productDescription.productName" label="菜名" width="180" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.productDescription !== null">{{ scope.row.productDescription.productName }}</span>
            <span v-if="scope.row.productDescription === null">{{ scope.row.taocan.taocanName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="productDescription.url" label="图片" width="100" align="center">
          <template slot-scope="scope">
            <img v-if="scope.row.productDescription !== null" :src="scope.row.productDescription.url" class="image"
              align="center">
            <img v-if="scope.row.productDescription === null" src="http://43.138.211.217:9000/misp-minio/taocan.jpg"
              class="image" align="center">
          </template>
        </el-table-column>
        <el-table-column prop="price" label="单价" width="100" align="center" />
        <el-table-column prop="quantity" label="数量" width="100" align="center" />
        <el-table-column prop="totalPrice" label="价格" width="100" align="center" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="small" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">取消</el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-dialog>

    <el-dialog :title="title" :visible.sync="taocanOpen" append-to-body>
      <el-table :data="taocanItemFixedList" style="width: 100%" border max-height="450">
        <el-table-column label="固定选项">
          <el-table-column prop="productName" label="菜名" width="180" align="center" />
          <el-table-column prop="categoryName" label="类别" width="150" align="center" />
          <el-table-column prop="quantity" label="数量" width="100" align="center" />
          <el-table-column prop="price" label="原价" align="center" />
        </el-table-column>
      </el-table>

      <el-table ref="selectedTableRef" :data="taocanItemSelectedList" style="width: 100%" border max-height="450"
        @selection-change="handleSelectionChange">
        <el-table-column :label="'可选选项（从下列选择'+ selectNum +'项）'">
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column prop="productName" label="菜名" width="180" align="center" />
          <el-table-column prop="categoryName" label="类别" width="150" align="center" />
          <el-table-column prop="quantity" label="数量" width="100" align="center" />
          <el-table-column prop="price" label="原价" width="150" align="center" />
          <el-table-column prop="addprice" label="加价" width="150" align="center" />
        </el-table-column>
      </el-table>

      <!-- 数据提交操作按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

    </el-dialog>

    <el-dialog :title="title" :visible.sync="paymentOpen" append-to-body>
      <el-form ref="makePaymentForm" :model="makePaymentForm" size="small" label-width="68px">
        <el-form-item label="座位号" prop="seatNumber">
          <el-input v-model="seatData.seatNumber" disabled />
        </el-form-item>
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="orderInfo.orderNo" disabled />
        </el-form-item>
        <el-form-item label="应付金额">
          <el-input v-model="orderInfo.total" />
        </el-form-item>
        <el-form-item label="付款金额" prop="cashTendered">
          <el-input v-model="makePaymentForm.cashTendered" />
        </el-form-item>
        <el-form-item label="找零">
          <el-input v-model="changeDue" disabled />
        </el-form-item>
        <el-form-item>
          <el-button type="danger" size="mini" @click="makePayment">现金支付</el-button>
          <el-button type="primary" size="mini" @click="payment">支付宝</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="comfirm">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    listAll
  } from '@/api/pos/category'
  import {
    listProductByPage
  } from '@/api/pos/product'
  import {
    makeNewOrder,
    enterItem,
    getOrderInfoByseatNumber,
    delOrderItem,
    updateOrderItem,
    handUpOrder,
    pendingOrder,
    endOrder,
    payment,
    makePayment
  } from '@/api/order/order'
  import {
    listTaocanByPage,
    listTaocanItem
  } from '@/api/order/taocan'
  import {
    cancelOrder,
    cancelOrderItem
  } from '@/api/pos/orderManage'
  export default {
    name: 'PlaceAnOrder',
    data() {
      return {
        seatData: {
          seatNumber: null,
          customerNumber: null
        },
        activeName: '1',
        categoryOptions: [],
        conheight: {
          height: ''
        },
        dataList: [],
        // 遮罩层
        loading: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          productSn: null,
          productName: null,
          categoryId: 1
        },
        // 总条数
        total: 0,
        enterItemForm: {},
        makePaymentForm: {},
        orderInfo: {},
        changeDue: 0,
        saleItemList: [],
        isNewOrder: null,
        title: '',
        open: false,
        hasOrderItemList: [],
        taocanOpen: false,
        taocanItemFixedList: [],
        taocanItemSelectedList: [],
        selectNum: null,
        paymentOpen: false

      }
    },
    watch: {
      '$route.path': {
        handler(newName, oldName) {
          if (newName === '/order/placeAnOrder') {
            this.getSeatData()
            this.getOrder()
          }
        },
        immediate: true // 首次加载是否进行监听
      }
    },

    mounted() {

    },

    created() {
      this.getSeatData()
      this.getCategoryOptions()
      this.getHeight()
      this.getList()
      this.getOrder()
    },

    methods: {
      getSeatData() {
        this.seatData.seatNumber = this.$route.query.seatNumber
        this.seatData.customerNumber = this.$route.query.customerNumber
      },

      /** 查询下拉列表选型 */
      getCategoryOptions() {
        // 访问后端接口，查外键所有对象
        // 结果赋值this.categoryOptions
        listAll().then(response => {
          this.categoryOptions = response.data
        })
      },

      getHeight() {
        this.conheight.height = window.innerHeight - 130 + 'px'
      },

      /** 查询数据列表 */
      getList() {
        this.loading = true
        // 结果赋值this.dataList
        listProductByPage(this.queryParams).then(response => {
          this.dataList = response.data.list
          this.total = response.data.total
          this.loading = false
          this.activeName = response.data.list[0].categoryId.toString()
        })
      },

      //获取套餐内容
      getTaocan() {
        this.loading = true
        // 结果赋值this.dataList
        const querydata = {
          pageNum: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize
        }
        listTaocanByPage(querydata).then(response => {
          this.dataList = response.data.list
          this.dataList.forEach((item) => {
            item.productName = item.taocanName
            item.price = item.taocanPrice
            item.url = 'http://43.138.211.217:9000/misp-minio/taocan.jpg'
          })
          this.total = response.data.total
          this.loading = false
          this.activeName = '21'
        })
      },

      //切换菜单目录
      handleClick() {
        this.queryParams.pageNum = 1
        if (this.activeName === '21') {
          this.getTaocan()
        } else {
          this.queryParams.categoryId = parseInt(this.activeName)
          this.getList()
        }
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        //this.queryParams.categoryId = null
        this.getList()
        // this.activeName = this.dataList[0].categoryId.toString()
      },

      /** 重置按钮操作 */
      resetQuery() {
        //this.$refs.queryForm.resetFields()
        this.queryParams.productName = null
        this.getList()
      },

      /** 处理分页 */
      handleSizeChange(val) {
        this.queryParams.pageSize = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.queryParams.pageNum = val
        this.getList()
      },

      // 清空界面数据
      clear() {
        this.orderInfo = {}
        this.saleItemList = []
        this.enterItemForm = {
          itemSn: '',
          seatNumber: '',
          name: '',
          identity: '',
          quantity: 1
        }
        this.makePaymentForm = {
          cashTendered: 0,
          orderNo: ''
        }
        this.changeDue = 0
      },

      // 步骤1：创建新的订单
      makeNewOrder() {
        this.clear()
        makeNewOrder(this.seatData).then(response => {
          this.orderInfo = response.data
        })
        this.orderInfo.customerNumber = this.seatData.customerNumber
      },
      // 获取已有订单
      getOrderInfoByseatNumber() {
        this.clear()
        getOrderInfoByseatNumber(this.seatData).then(response => {
          const num1 = 0
          const num2 = 0
          this.orderInfo = response.data
          this.saleItemList = response.data.currentorderItems
          this.hasOrderItemList = response.data.orderItems
          this.hasOrderItemList.forEach((item) => {
            item.totalPrice = Number(item.quantity) * Number(item.price)
            num1 += item.totalPrice
          })
          this.saleItemList.forEach((iitem) => {
            num2 += Number(item.quantity) * Number(item.price)
          })
          this.orderInfo.total = num1 + num2
        })
      },
      // 获取订单
      getOrder() {
        if (this.$route.query.seatStatus === '就餐中') {
          this.getOrderInfoByseatNumber()
        } else {
          this.makeNewOrder()
        }
      },
      // 步骤2：提交输入商品
      enterItem(data) {
        if (this.activeName === '21') {
          this.handTaocan(data)
          this.enterItemForm = {
            orderNo: this.orderInfo.orderNo,
            itemSn: data.taocanSn,
            seatNumber: this.seatData.seatNumber,
            name: data.taocanName,
            identity: 1,
            quantity: 1
          }
        } else {
          this.enterItemForm = {
            orderNo: this.orderInfo.orderNo,
            itemSn: data.productSn,
            seatNumber: this.seatData.seatNumber,
            name: data.productName,
            identity: 0,
            quantity: 1
          }
          enterItem(this.enterItemForm).then(response => {
            this.orderInfo.total = response.data
            /**const index = this.saleItemList.findIndex((item) => item.productSn === this.enterItemForm.itemSn)
            if (index === -1) {
              data.quantity = 1
              this.saleItemList.push(data)
              console.log(-1)
            } else {
              this.saleItemList[index].quantity = Number(this.saleItemList[index].quantity) + Number(this
                .enterItemForm.quantity)
            }
            console.log(this.saleItemList)**/
            this.getOrderInfoByseatNumber()
          })
        }
      },

      // 修改一行订单明细数量
      handleChangeQuantity(data) {
        const changeData = {
          orderNo: this.orderInfo.orderNo,
          seatNumber: this.seatData.seatNumber,
          quantity: data.quantity
        }
        if (data.productDescription !== null) {
          changeData.itemSn = data.productDescription.productSn
        } else {
          changeData.itemSn = data.taocan.taocanSn
        }
        updateOrderItem(changeData).then(response => {
          this.$message({
            type: 'success',
            message: '修改数量成功!'
          })
          this.orderInfo.total = response.data
        })
      },

      // 删除订单项
      delOrderItem(index, data) {
        this.$confirm('确定删除该商品?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.saleItemList.splice(index, 1)
          const delData = {
            orderNo: this.orderInfo.orderNo,
            // seatNumber: this.seatData.seatNumber
          }
          if (data.productDescription !== null) {
            delData.itemSn = data.productDescription.productSn
          } else {
            delData.itemSn = data.taocan.taocanSn
          }
          delOrderItem(delData).then(response => {
            this.orderInfo.total = response.data
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },

      // 订单挂起
      handUpOrder() {
        handUpOrder(this.seatData.seatNumber).then(response => {
          this.getOrderInfoByseatNumber()
          this.$message({
            message: '挂单成功',
            type: 'success'
          })
        })
        this.$router.push({
          path: 'seat'
        })
      },

      // 下单
      pendingOrder() {
        pendingOrder(this.seatData.seatNumber).then(response => {
          this.getOrderInfoByseatNumber()
          this.$message({
            message: '下单成功',
            type: 'success'
          })
        })
      },

      // 结算
      endOrder() {
        endOrder(this.seatData.seatNumber).then(response => {
          this.orderInfo.total = response.data
          this.makePaymentForm.orderNo = this.orderInfo.orderNo
          this.title = '支付'
          this.paymentOpen = true
          this.$message({
            message: '结算成功',
            type: 'success'
          })
        })
      },

      // 支付宝
      payment() {
        const paymentData = {
          subject: 'resturant',
          totalAmount: this.orderInfo.total,
          traceNo: this.seatData.seatNumber
        }
        payment(paymentData).then(response => {
          // 跳转支付页面
          document.querySelector('body').innerHTML = response.msg
          document.forms[0].submit()
          this.paymentOpen = false
        })
        this.getOrderInfoByseatNumber()
      },

      // 现金支付
      makePayment() {
        makePayment(this.makePaymentForm).then(response => {
          const res = response.data
          if (res >= 0) {
            this.changeDue = response.data
            this.$message({
              message: '支付成功',
              type: 'success'
            })
          } else {
            this.$message('余额不足')
          }
        })
        //this.getOrderInfoByseatNumber()
      },

      // 已下单菜品
      hasOrderItem() {
        this.open = true
        this.title = '已下单菜品'
      },

      // 点击查看套餐内容
      handTaocan(data) {
        const querydata = {
          taocanSn: data.taocanSn
        }
        listTaocanItem(querydata).then(response => {
          this.taocanItemFixedList = []
          this.taocanItemSelectedList = []
          this.title = '套餐内容'
          this.taocanOpen = true
          response.data.forEach((item) => {
            if (item.taocanType === 1) {
              this.taocanItemFixedList.push(item)
            } else {
              this.taocanItemSelectedList.push(item)
            }
          })
          this.selectNum = this.taocanItemSelectedList[0].highestOption
        })
      },

      //选择可选内容
      handleSelectionChange(val) {
        console.log(val)
        if (val.length > this.selectNum) {
          this.$message({
            type: 'info',
            message: '超出可选数量'
          })
        } else {
          this.enterItemForm.orderTaocanItem = val
          this.taocanItemFixedList.forEach((item) => {
          this.enterItemForm.orderTaocanItem.push(item)
          })
        }
      },

      //确定添加套餐
      submitForm() {
        enterItem(this.enterItemForm).then(response => {
          this.orderInfo.total = response.data
          /**const index = this.saleItemList.findIndex((item) => item.taocan.taocanSn === this.enterItemForm.itemSn && item.taocan.orderTaocanItem === this.enterItemForm.orderTaocanItem)
          if (index === -1) {
            data.quantity = 1
            this.saleItemList.push(data)
            console.log(-1)
          } else {
            this.saleItemList[index].quantity = Number(this.saleItemList[index].quantity) + Number(this
              .enterItemForm.quantity)
          }
          console.log(this.saleItemList)**/
          this.getOrderInfoByseatNumber()
        })
        this.taocanOpen = false
      },

      cancel() {
        this.taocanOpen = false
        this.paymentOpen = false
      },

      // 支付结束确认跳转
      comfirm() {
        this.paymentOpen = false
        this.$router.push({
          path: 'seat'
        })
      },

      // 撤单
      handleDelete(row) {
        const query = {}
        if (row.itemIdentity === 0) {
          query.orderNo = this.orderInfo.orderNo
          query.itemSn = row.productDescription.productSn
          query.seatNumber = this.seatData.seatNumber
          query.name = row.productDescription.productName
          query.quantity = row.quantity
          query.identity = '0'
        } else {
          query.orderNo = this.orderInfo.orderNo
          query.itemSn = row.taocan.taocanSn
          query.seatNumber = this.seatData.seatNumber
          query.name = row.taocan.taocanSn
          query.quantity = row.quantity
          query.identity = row.itemIdentity
          query.orderTaocanItem = row.taocan.orderTaocanItem
        }
        this.$confirm('是否确认取消该菜品?', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(function () {
            return cancelOrderItem(query)
          })
          .then(() => {
            this.getOrderInfoByseatNumber() // 刷新数据
            this.$message.success('取消成功')
          })
          .catch(() => {
            this.$message('取消失败')
          })
      },

      // 取消订单
      cancelOrder() {
        const query = {
          seatNumber: this.seatData.seatNumber
        }
        this.$confirm('是否确认取消该订单?', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(function () {
            return cancelOrder(query)
          })
          .then(() => {
            this.$message.success('取消成功')
            this.$router.push({
              path: 'seat'
            })
          })
          .catch(() => {
            this.$message('取消失败')
          })
      },
    }
  }
</script>

<style scoped>
  .box-card {
    height: 100%;
    overflow-y: auto
  }

  .menuCard {
    margin: 3px
  }

  .price {
    color: blue;
    font-size: 13px
  }

  .bottom {
    margin-top: 13px;
    line-height: 12px;
  }

  .button {
    padding: 0;
    float: right;
  }

  .image {
    width: 100%;
    height: 80px;
    display: block;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both
  }
</style>
